package com.yupi.yupao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupao.common.*;
import com.yupi.yupao.config.JWTConfig;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.mapper.UserMapper;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.request.UserLoginRequest;
import com.yupi.yupao.model.domain.request.UserRegisterRequest;
import com.yupi.yupao.model.dto.WxLoginDto;
import com.yupi.yupao.model.vo.WxLoginVO;
import com.yupi.yupao.model.vo.WxUserLoginVO;
import com.yupi.yupao.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.yupi.yupao.contant.UserConstant.ADMIN_ROLE;
import static com.yupi.yupao.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 *

 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
@CrossOrigin()
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private JWTConfig jwtConfig;
    @Resource
    private RedisMatchHistoryService redisMatchHistoryService;
    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 校验
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }
    @PostMapping("wxLogin")
    public BaseResponse<WxUserLoginVO> wxLogin(@RequestBody WxLoginDto wxLoginDto) throws IOException {
        log.info("微信登录");

        User user = userService.checkLogin(wxLoginDto);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",user.getId());
        //创建token
        String token = jwtConfig.createToken(user.getId().toString());
        //设置值
        WxUserLoginVO userLoginVO = WxUserLoginVO.builder().id(user.getId()).token(token).openId(user.getOpenId()).build();
        //返回
        return ResultUtils.success(userLoginVO);

    }


    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {

        Long userId=BaseContext.getCurrentId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }


    @ApiOperation(value = "搜索用户（仅管理员）")
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username) {
        Long userId = BaseContext.getCurrentId();

        if (!isAdmin(userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageNum,long pageSize, HttpServletRequest request) {
//        User loginUser = userService.getLoginUser(request);

        Long userId = BaseContext.getCurrentId();
//        String redisKey = String.format("yupao:user:recommend:%s", userId+pageNum);
//        //先查缓存，
//        Page<User> pageList = (Page<User>) redisTemplate.opsForValue().get(redisKey);
//        if(pageList!=null){
//            return ResultUtils.success(pageList);
//        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        Page<User> pageList =userService.page(new Page<>(pageNum,pageSize),queryWrapper);
//        try {
//            redisTemplate.opsForValue().set(redisKey,pageList,3, TimeUnit.HOURS);
//        }catch (Exception e){
//            log.error("redis error",e);
//        }

//        List<User> userList = userService.list(queryWrapper);
        pageList.getRecords().stream().forEach(item->{
            if(item.getTags()==null){
                item.setTags("[]");
            }
        });

        return ResultUtils.success(pageList);
    }
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchTags(@RequestParam(required=false) List<String> tagList){
        if(CollectionUtils.isEmpty(tagList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userByTagNameList = userService.getUserByTagNameList(tagList);
        return ResultUtils.success(userByTagNameList);
    }
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        Long userId = BaseContext.getCurrentId();
        if (!isAdmin(userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user) {
        if (user==null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取登录用户信息
        Long userId = BaseContext.getCurrentId();
        redisMatchHistoryService.clearMatchedUsers(userId);
        User userInfo = userService.getById(userId);//数据多会有点慢
        user.setId(userId);
        Integer result= userService.updateUser(user,userInfo);
        return ResultUtils.success(result);
    }


    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }
    private Boolean isAdmin(Long userId){
        User user = userService.getById(userId);
        return user!=null&&user.getUserRole()==ADMIN_ROLE;
    }
    @ApiOperation("用户匹配(单个)")
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num,HttpServletRequest request){
        if(num<=0||num>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long userId = BaseContext.getCurrentId();
        log.info("登录账户ID："+userId);
        User userInfo = userService.getById(userId);
        log.info("登录账户："+userInfo);
        return ResultUtils.success(userService.matchUsers(num,userInfo));
    }
    @GetMapping("/test")
    public BaseResponse<String> testApi(){
        Long currentId = BaseContext.getCurrentId();
        log.info("userId"+currentId);
        log.info("请求成功");
        return ResultUtils.success("请求成功");
    }
    @GetMapping("/search/username")
    public BaseResponse<List<User>> searchUserByUsername(String username){
        return ResultUtils.success(userService.list(new QueryWrapper<User>().like("username",username)));
    }

}
